<template lang="html">
  <div class="main-page" id="store-page">
    <!-- 标题 -->
    <!-- <van-nav-bar class="main-header" title="提现" :left-arrow="true" :fixed="true" :z-index="11" @click-left="onClickLeft"/> -->
    <nav-bar :title="'申请提现'" @goBack="onClickLeft"/>
    <!-- 主体内容 -->
    <div class="main-content has-main-tabbar has-header-space">
      <div class="withdrawal-wrap">
       <div style="color:#666666;font-size:18px;padding:15px;"> 可申请提现金额 </div>
       <van-row>
          <van-col span="3" style="height:40px; line-height:40px">
            <span style="position:relative;color:#17273A;font-size:35px;padding-left:15px;">¥</span>
          </van-col>
           <van-col span="15" style="height:40px">
             <van-field style="padding:0; line-height:40px" v-model="amount" type="number" step="0.01" clearable :placeholder="userData.asset_info.real_balance" input-align="left" @input="amountChange"></van-field>
          </van-col>
          <van-col span="6">
          <div class="reflect-all" @click="allReflec">全部提现</div>
          </van-col>
        </van-row>
        <div>
         <div class="reflect-ok">最低申请提现额度50.00元，额外扣除¥{{rateMoney.rate_amount}}<span class="decoration" @click="getShowTip">服务费</span> 费率{{rateMoney.rate}} </div>
      </div>
    </div>
  <!-- 提现方式 -->
  <div class="withdrawal-way" v-if="bankList.length">
    <div class="withdrawal-name">提现方式</div>
    <div v-if="values === '请选择'" style="color: #C3CDD6;" class="withdrawal-record">{{values}}</div>
    <div v-else style="color: #999999;" class="withdrawal-record">{{values}}</div>
    <!-- <img style="position:absolute;top:15px;right:10px;width:22px;height:22px;" src="https://mjmh.meijiameihuo.com/wechat/images/icon/arrow-right.png" alt=""> -->
 </div>
 <div class="withdrawal-way" @click="addBank" v-if="!bankList.length">
   <div class="withdrawal-name">添加银行卡</div>
   <img @click="withdrawalShow" style="position:absolute;top:15px;right:10px;width:22px;height:22px;" src="https://mjmh.meijiameihuo.com/wechat/images/icon/arrow-right.png" alt="">
</div>
  <!-- 方式选择 -->
  <van-popup v-model="shows_bank_list" position="bottom" bind:click-overlay="closeShop" custom-class="popup-height" >
       <van-picker :columns="bankList" show-toolbar title="选择提现方式" @cancel="closeShop" @confirm="confirm" value-key="text" />
  </van-popup>
  <!-- 银行卡-->
  <template v-if="seleckBank.bankcard_number">
    <div class="seleckBank">
      <div class="user_info">
        姓名： <span>{{seleckBank.user_name}}</span>
      </div>
      <BankItem :item="seleckBank" action_txt="更换银行卡>"></BankItem>
    </div>
    <router-link :to="{path: '/merber/bankManagement', query: {u_id: this.userData.user_info.user_id}}">
      <div class="bank">银行卡管理</div>
    </router-link>
  </template>
   <template v-else></template>
   <div class="withdrawal-apply">
     <div style="color:#999999;font-size:12px;margin:10px 10px 0 10px;">平台将每周三做为付款日（法定节假日顺延），每周一为审核日，审核上周所有的提现申请；审核时间为1个工作日；付款会在审核成功后2个工作日内完成。</div>
     <van-button size="large"  :class="!this.isError && this.seleckBank.bankcard_number ? '' : 'disable'" @click="submit">申请提现</van-button>
      <!-- 密码框 -->
       <van-popup v-model="payShow" bind:click-overlay="payCloseShop">
         <div class="close-header">
           <div style="height:55px;line-height:55px;border-bottom:1px solid #CBCBCB;color:#333333;font-size:16px;text-align:center;">请输入您的支付密码</div>
            <span class="close"  @click="payCloseShop">X</span>
         </div>
             <div class="write-phonenum">
               <!-- <ul class="write-input clearfix">
                 <input type="password"  ref="input" maxlength="6" class="realInput" v-model="realInput" autofocus @keyup="getNum()" @keydown="delNum()">
                 <li v-for="(disInput, index) in disInputs" :index="index" :key="index"><input type="text" maxlength="1" disabled  v-model="disInput.value"></li>
               </ul> -->
               <van-password-input
                  :value="disInputs"
                  @focus="showKeyboard = true"
                />
             </div>
            <div style="color:#E91F3F;font-size:15px;float:right;padding-right:20px;" @click="forgetPwd">忘记密码？</div>
      </van-popup>
   </div>
   <van-number-keyboard
      :show="payShow"
      @input="getNum"
      @delete="delNum"
      @blur="showKeyboard = false"
    />
    <van-toast id="van-toast" />
    <van-dialog v-model="show_tips" title="提现综合服务费" confirm-button-text="我知道了" :lockScroll="true">
      <div class="reflect_tips">
        <div class="tips_content">
          <h3>合作须知</h3>
          <p>美家美货平台每天有大量的超级会员通过自购省钱/分享赚钱方式，获得平台返利。平台在为超级会员创造大量收益，为社会提供大量就业机会的同时，自身却不可避免地面临财务及税务风险（即支付给会员的返利如何入账？），为了合法合规地执行国家税收法则，美家美货在国家相关法律的规定范围之内，对每位超级会员所赚取的返利进行税务代扣。</p>
          <h3>政策依据</h3>
          <p>《中国人民共和国税收征收管理法实施细则》</p>
          <p>第四十四条税务机关根据有利于税收控管和方便纳税的原则，可以按照国家有关规定委托有关单位和人员代征零星分散和异地缴纳的税收，并发给委托代征证书。受托单位和人员按照代征证书的要求，以税务机关的名义依法征收税款，纳税人不得拒绝；纳税人拒绝的，受托代征单位和人员应当及时报告税务机关。</p>
          <p>《国家税务总局个体工商户个人所得税计税办法》</p>
          <p>第三条本办法所称个体工商户包括：（三）其他从事个体生产、经营的个人。</p>
          <p>《中华人民共和国税收征收管理法》</p>
          <p>第三十七条对未按照规定办理税务登记的从事生产、经营的纳税人以及临时从事经营的纳税人，由税务机关核定其应纳税额。</p>
          <h3>根据法律规定，数以千万计的自由职业者自行到税务机关代开发票的办法不可行。</h3>
          <h3>管理办法</h3>
          <p>美家美货委托第三方劳务服务公司统一与会员签订《共享经济合作伙伴协议》，为所有会员集中以自由职业者方式申报个人所得税，第三方公司收取10%综合服务费【含个人应缴税额】后向美家美货开具全额增值税服务发票。会员提现到账金额为每次通过美家美货平台申请提现金额的90%，提现到账后无须再就此笔收入自行向税务局申报个人收入所得。</p>
        </div>
      </div>
    </van-dialog>
    </div>
  </div>
</template>

<script>
// import { Toast } from 'vant'
// import { Dialog } from 'vant'
import { JSEncrypt } from 'jsencrypt'
import NavBar from '@/components/global/nav-bar.vue'
import BankItem from '@/components/common/bankitem'
import Tool from '@/utils/tool.js'

export default {
  components: { NavBar, BankItem },
  data () {
    return {
      type: '',
      show_tips: false,
      shows: false,
      payShow: false,
      values: '银行卡',
      amount: null,
      columns: [
        { text: '微信' },
        { text: '银行卡' }
      ],
      userData: {
        user_info: {
          user_id: 10001,
          user_account: 'shopsuite',
          user_nickname: 'shopsuite',
          user_mobile: '17732122345',
          lev_code: 'VIP',
          invite_id: 'aoeyuv',
          parent_invite: 'qe21f25a',
          state: null,
          lev_name: '超级会员',
          icon: null
        },
        asset_info: {
          amount: 0,
          day_amount: 0,
          month_amount: 0,
          balance: 0,
          real_balance: 0
        }
      },
      user_nickname: '',
      isError: true,
      isIphoneX: false,
      showType: 'password', // 如果是密码换成'password'
      messagepacket: false,
      packets: [],
      disInputs: '',
      realInput: '',
      pushShow: false,
      bankList: [],
      ids: null,
      shows_bank_list: false,
      seleckBank: {},
      rateMoney: {
        rate: '10%',
        rate_amount: 0
      }
    }
  },
  created () {
    if (this.$route.query.ids) {
      this.ids = this.$route.query.ids
    }
    this.getUserInfo()
    this.getBankList(this.ids)
    this.getRate(0)
    if (!localStorage.getItem('apply_reflect_tips')) {
      this.show_tips = true
      localStorage.setItem('apply_reflect_tips', true)
    }
  },
  mounted () {
    // 将backToday方法绑定到window下面，提供给外部调用
    window['getUpload'] = () => {
      this.getBankList()
    }
  },
  methods: {
    addBank () {
      this.$router.push('/merber/addBank')
    },
    openSelectBank () {
      this.shows_bank_list = true
    },
    closeShop () {
      this.shows_bank_list = false
    },
    confirm (value) {
      this.shows_bank_list = false
      this.seleckBank = value
    },
    getBankList (id) {
      var data = id ? {} : { card_status: 0 }
      return new Promise((resolve, reject) => {
        this.$Axios({ url: 'user_bankinfo', params: data, method: 'get' }).then((res) => { // 请求成功
          if (res.return_code === '0000' && res.data.list.length > 0) {
            var data = res.data.list.map((item) => {
              item.text = item.bank_name + item.bankcard_number.substr(-4)
              return item
            })
            this.bankList = data
            this.seleckBank = data[0]
            this.amountChange(this.amount)
          } else {
            console.log(res.return_msg)
          }
          resolve(res)
        }).catch((error) => { // 请求失败
          this.$_requestInterceptor('error', error)
          reject(error)
        })
      })
    },
    getNum (key) {
      // for (var i = 0; i < this.realInput.length; i++) {
      //   console.log(this.realInput.length)
      //   this.disInputs[i].value = this.realInput.charAt(i)
      //   if (this.realInput.length === 6) {
      //     this.passwordComplete(this.realInput)
      //     console.log(this.realInput)
      //     this.realInput = ''
      //     this.disInputs = [{ value: '' }, { value: '' }, { value: '' }, { value: '' }, { value: '' }, { value: '' }]
      //     this.payShow = false
      //   }
      // }
      this.disInputs = (this.disInputs + key).slice(0, 6)
      if (this.disInputs.length === 6) {
        this.passwordComplete(this.disInputs)
        this.realInput = ''
        this.payShow = false
      }
    },
    delNum () {
      // var oEvent = window.event
      // if (oEvent.keyCode === 8) {
      //   if (this.realInput.length > 0) {
      //     this.disInputs[ this.realInput.length - 1 ].value = ''
      //   }
      // }
      this.disInputs = this.disInputs.slice(0, this.disInputs.length - 1)
    },
    enterPwd () {
      this.pushShow = true
    },
    clearNewPassword () {
      this.password = []
    },
    onClickLeft () {
      this.$router.go(-1)
    },

    withdrawalShow () {
      // this.shows = true
    },

    amountChange (e) {
      let reg = /^\d+(\.\d{0,2})?$/
      const val = parseFloat(e)
      if (val) {
        if (reg.test(val)) {
          let num = Math.floor(val * 100) / 100
          if (num >= 50) {
            if (num <= this.userData.asset_info.real_balance) {
              this.isError = false
              this.amount = val
            } else {
              this.isError = true
            }
          }
          this.getRate(val)
        } else {
          // this.$toast({ message: '提现金额限制小数点后两位' })
          let num = Math.floor(val * 100) / 100
          this.amount = num.toFixed(2)
          this.getRate(num)
        }
      } else {
        this.isError = true
      }
    },
    getRate (val) {
      if (!val) val = 0
      var data = {
        type: 'cash_rate',
        cash_amount: parseFloat(val)
      }
      return new Promise((resolve, reject) => {
        this.$Axios({ url: 'user_cash_rule', data: data, method: 'post' }).then((res) => { // 请求成功
          if (res.return_code === '0000') {
            if (res.data) {
              this.rateMoney = res.data
            }
          }
          resolve(res)
        }).catch((error) => { // 请求失败
          this.$_requestInterceptor('error', error)
          reject(error)
        })
      })
    },
    forgetPwd () {
      console.log('忘记了密码')
      let isClient = Tool.isClient()
      if (isClient) {
        window.location.href = 'payorder://'
      } else {
        let isMini = sessionStorage.getItem('isMini')
        if (isMini) {
          window.wx.miniProgram.navigateTo({ url: '/pages/personal_center/setup/initial-password/initial-password' })
        }
      }
    },
    payCloseShop () {
      this.payShow = false
      this.realInput = ''
      this.disInputs = [{ value: '' }, { value: '' }, { value: '' }, { value: '' }, { value: '' }, { value: '' }]
      this.clearNewPassword()
    },
    onTapFocus: function () {
      this.isFocus = true
    },
    passwordComplete (val) {
      console.log(val)
      if (val) {
        // rsa加密
        var encrypt = new JSEncrypt()
        var pub = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQD5ggRJWAQJ0ZmYZJC8pz4zOmWkZ4xh2o/GfI4DNKZHo9TlYsq810h5QQLv58U+zXPTstLjgb6WfdKR8MTH5wi7LOwKUHIl20CsPz1WnYUWwr+vKcQG9Wu4x4DXDxqFyuaCNOhRqtKqNYu/FFUsJL4riYr0zn25Ee + r3v9gh7u4fQIDAQAB'
        let publicKey = '-----BEGIN PUBLIC KEY-----' + pub + '-----END PUBLIC KEY-----' // 从后台获取公钥，这里省略，直接赋值
        encrypt.setPublicKey(publicKey)
        let encStr = encrypt.encrypt(val)
        this.applyWithdrawals(encStr)
        console.log(encStr)
      }
    },
    change (val) {
      console.log(val)
    },
    allReflec () {
      this.amount = this.userData.asset_info.real_balance
      this.amountChange(this.amount)
    },
    submit () {
      let reg = /^\d+(\.\d{0,2})?$/
      const val = this.amount
      if (reg.test(val)) {
        if (parseFloat(val) >= 50) {
          console.log(parseFloat(val))
          if (parseFloat(val) > this.userData.asset_info.real_balance) {
            this.$toast({ message: '可申请提现金额不足，请重新输入！' })
          } else {
            this.checkBank()
          }
        } else {
          this.$toast({ message: '最低提现额度为50元' })
        }
      } else {
        if (!val) {
          this.$toast({ message: '请输入提现金额！' })
        } else {
          this.$toast({ message: '提现金额限制小数点后两位！' })
        }
        this.isError = true
        this.amount = val
      }
    },
    checkBank () {
      if (this.seleckBank.bankcard_number) {
        this.getUserPassword()
      } else {
        this.$dialog.confirm({
          message: '请添加银行卡',
          confirmButtonText: '立即添加',
          cancelButtonText: '我再看看'
        }).then(() => {
          this.$router.push('/merber/addBank')
        }).catch(() => {
          console.log('取消')
        })
      }
    },
    getUserPassword () { // 获取信息判断是否设置密码
      var data = {
        type: 'is_exist'
      }
      return new Promise((resolve, reject) => {
        this.$Axios({ url: 'user_pay', params: data, method: 'get' }).then((res) => { // 请求成功
          console.log(res)
          if (res.return_code === '1111') {
            console.log('我竟来了')
            this.$dialog.confirm({
              message: '请先完成支付密码设置',
              confirmButtonText: '去设置',
              cancelButtonText: '取消'
            }).then(() => {
              let isClient = Tool.isClient()
              if (isClient) {
                window.location.href = 'payorder://'
              } else {
                let isMini = sessionStorage.getItem('isMini')
                if (isMini) {
                  window.wx.miniProgram.navigateTo({ url: '/pages/personal_center/setup/initial-password/initial-password' })
                }
              }
            }).catch(() => {
              console.log('取消')
            })
            console.log('请求成功')
          } else {
            this.payShow = true
          }
          resolve(res)
        }).catch((error) => { // 请求失败
          this.$_requestInterceptor('error', error)
          reject(error)
        })
      })
    },
    applyWithdrawals (password) { // 申请提现
      if (password) {
        this.payShow = false
        this.$toast.loading({
          mask: true
        })
        var data = {
          pay_password: password,
          cash_type: 2,
          amount: Number(this.amount) * 100,
          bank_card_nu: this.seleckBank.bankcard_number,
          bank_id: this.seleckBank.id,
          bank_name: this.seleckBank.bank_name
        }
        return new Promise((resolve, reject) => {
          this.$Axios({ url: 'user_cash', data, method: 'post' }).then((res) => {
            if (res.return_code === '0000') {
              this.realInput = ''
              this.disInputs = [{ value: '' }, { value: '' }, { value: '' }, { value: '' }, { value: '' }, { value: '' }]
              this.payShow = false
              this.$toast({ message: res.data, forbidClick: true })
              setTimeout(() => {
                let isMini = sessionStorage.getItem('isMini')
                if (isMini) {
                  window.wx.miniProgram.navigateBack()
                } else {
                  this.$router.go(-1)
                }
                // this.$router.back(0)
              }, 3000)
            } else if (res.return_code === '1112') {
              this.$dialog.confirm({
                message: res.return_msg,
                confirmButtonText: '忘记密码',
                cancelButtonText: '重新输入'
              }).then(() => {
                let isClient = Tool.isClient()
                if (isClient) {
                  window.location.href = 'payorder://'
                } else {
                  let isMini = sessionStorage.getItem('isMini')
                  if (isMini) {
                    window.wx.miniProgram.navigateTo({ url: '/pages/personal_center/setup/initial-password/initial-password' })
                  }
                }
                this.realInput = ''
                this.disInputs = [{ value: '' }, { value: '' }, { value: '' }, { value: '' }, { value: '' }, { value: '' }]
              }).catch(() => {
                this.realInput = ''
                this.disInputs = [{ value: '' }, { value: '' }, { value: '' }, { value: '' }, { value: '' }, { value: '' }]
                this.payShow = true
              })
            } else {
              this.$toast(res.return_msg)
            }
            resolve(res)
          }).catch((error) => {
            this.$_requestInterceptor('error', error)
            this.$toast('请求失败')
            reject(error)
          })
        })
      }
    },
    getUserInfo () { // 获取用户信息
      var data = {}
      return new Promise((resolve, reject) => {
        this.$Axios({ url: 'profile', data, method: 'get' }).then((res) => { // 请求成功
          console.log(res)
          if (res.return_code === '0000') {
            if (res.data) {
              this.userData = res.data
              this.user_nickname = res.data.user_info.user_nickname.length > 10 ? res.data.user_info.user_nickname.substr(0, 10) + '...' : res.data.user_info.user_nickname
            }
            console.log('请求成功')
          } else {
            console.log('请求错误')
          }
          this.$toast.clear()
          resolve(res)
        }).catch((error) => { // 请求失败
          this.$toast.clear()
          this.$_requestInterceptor('error', error)
          reject(error)
        })
      })
    },
    getShowTip () {
      this.show_tips = true
    }
  }
}
</script>
<style lang="scss" scoped>
.van-overlay{z-index: 100 !important; background: #ccc}
.withdrawal-wrap{background-color:#fff;margin-bottom:10px;overflow-x:hidden;}
.bank{color:#4a90e2;font-size:14px;text-decoration:underline;background-color:#fff;text-align:right;padding:0px 15px; height:35px; line-height: 35px;}
.bank_list{background-color: #ffffff;padding:10px;text-align:center}
.seleckBank {padding: 0px 15px; background: #fff;}
.seleckBank .user_info { padding: 15px 0; font-size: 16px; color: #999999;}
.seleckBank .user_info span { color: #17273A};
.bank_item-text{position:absolute;bottom:30px;right:24%;font-size:14px;color:#fff}
.bank_item-text1{position:absolute;top:14px;right:19px;font-size:14px;color:#fff}
.replace-img{position:relative;width:90%;height:80px}
.replace-bank{position:absolute;top:40%;right:10%;color:#dfc399;font-size:12px;margin-left:10px}
.wx-num{color:#c3cdd6;font-size:24px}.sub{position:fixed!important;bottom:0;color:#fff!important;background-color:#e91f3f!important;border:0!important}
.wx-info{background-color: #ffffff;padding:18px 15px;}
.render-input{width:48px;height:48px;border:0.5px solid #CBCBCB;border-left:none;box-sizing:border-box;text-align:center}
.render-input:first-child{border-left:0.5px solid #eee}
.hidden-input{width:0;height:0}
.withdrawal-way{position:relative;height:50px;background-color:#ffffff;margin-bottom:1px;}
.withdrawal-name{
float:left;font-size:17px;font-weight:bold;color:#333333;padding:13px 15px;
}
.withdrawal-record{
float:right;font-size:17px;font-weight:bold;color:#333333;padding:13px 30px 13px 0;
}
.record{
  display:inline-block;color:#4A90E2;font-size:15px;padding:15px 15px 15px 0;
}
.reflect-ok{
 color:#999999;font-size:13px;padding:15px;background-color: #ffffff;
}
.reflect-all{
  color:#DDB074;font-size:16px;font-weight:bold;padding:15px 15px 15px 10px;
}
.close{
  position:absolute!important;
  right:20px;
  top:20px;
}
.close-header{
  position:relative;
  text-align: center;
  padding:0 16px 23px 16px;
}
.isIPX{bottom: 15px!important;
}
.isX{
  width:100%;
  height:15px;
  position: fixed;
  bottom:0;
  left:0;
  background-color: #FFFFFF;
}
 .write-phonenum{
   background: #fff;
   height:48px;
   margin-bottom:20px;
   padding: 0 10px;
 }
 .write-phonenum p{
   font-size: 14px;
   margin-left:30px;
   line-height:2;
 }
 .write-phonenum p span{color: #3b90d1;}
 .write-input {width:90%; margin:0px auto; position: relative;left:2.5%;right:0;}
 .write-input li{float: left;width:15%;height:48px; border:1px solid #CBCBCB;color: #333333; text-align: center; margin-left: -1px}
 .write-input li input{-webkit-appearance: none;-moz-appearance: none;-ms-appearance: none;resize: none;outline: none;border:0;width:100%;line-height: 48px;text-align: center;height: 48px;font-size:20px;}
 input:disabled {
     background-color: #ffffff;
 }
 .realInput{
   /* Keyword values */
   -webkit-appearance: none;
   -moz-appearance: none;
   -ms-appearance: none;
   resize: none;
   outline: none;
   border: 0;
   z-index: 3;
   position: absolute;
   width: 290px;
   height: 30px;
   line-height: 30px;
   background: none;
   display: block;
   opacity: 0;
   left: 50%;
   margin-left: -100%;
   top: 34px;
   opacity: 0;
   font-size: 0px;
   caret-color: transparent;
   color: #000;
   text-indent: -999em;
   font-size: 30px;
   top:1px;
 }
 input[type="tel"]:disabled{background-color: #fff;}
.withdrawal-apply .van-button.disable {
  opacity: 1; background: #D0D0D0 !important
}
.withdrawal-apply .van-popup {
  top:35%
}
.reflect_tips {
  font-size: 13px;
  padding: 15px;
  font-family:'Courier New', Courier, monospace;
}
.tips_content {
  max-height: 50vh;
  overflow: scroll;
  h3 { padding: 10px 0;}
}
.decoration {
  text-decoration: underline;
}
</style>
